package uebung06_h;

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class Line {
	double x1, x2, y1, y2;
	double a, b, d;
	void calc() {
		a = -(y2-y1);
		b = x2-x1;
		double norml = Math.sqrt(a*a+b*b);
		
		a /= norml;
		b /= norml;
		 
		d = a*x1+b*y1;
	}
	double getDistance(double x, double y) {
//		r_ * n_ -d;
		double upper = Math.min(y1, y2), lower = Math.max(y1, y2), left = Math.min(x1, x2), right = Math.max(x1, x2);
		if (Double.compare(y1-y2, 0)==0) {
			if (x<right && x>left) {
				return Math.abs(a*x+b*y-d);
			}
			else 
				return Math.sqrt(Math.min(((x-x1)*(x-x1)+(y-y1)*(y-y1)), ((x-x2)*(x-x2)+(y-y2)*(y-y2))));
		}
		else {
			if (y<lower && y>upper) {
				return Math.abs(a*x+b*y-d);
			}
			else 
				return Math.sqrt(Math.min(((x-x1)*(x-x1)+(y-y1)*(y-y1)), ((x-x2)*(x-x2)+(y-y2)*(y-y2))));
		}
	}
	
	public Line setLine(Line2D l) {
		this.x1 = l.getX1();
		this.x2 = l.getX2();
		this.y1 = l.getY1();
		this.y2 = l.getY2();
		this.calc();
		return this;
	}
	
	Point2D getNearest(double x, double y) {
//		r_ * n_ -d;
		double upper = Math.min(y1, y2), lower = Math.max(y1, y2), left = Math.min(x1, x2), right = Math.max(x1, x2);
		if (Double.compare(y1-y2, 0)==0) {
			if (x<right && x>left) {
				return new Point2D.Double(x-(a*x+b*y-d)*a, y-(a*x+b*y-d)*b);
			}
			else 
				if (((x-x1)*(x-x1)+(y-y1)*(y-y1))<((x-x2)*(x-x2)+(y-y2)*(y-y2))) {
					return new Point2D.Double(x1,y1);
				}
				else {
					return new Point2D.Double(x2,y2);
				}
		}
		else {
			if (y<lower && y>upper) {
				return new Point2D.Double(x-(a*x+b*y-d)*a, y-(a*x+b*y-d)*b);
			}
			else 
				if (((x-x1)*(x-x1)+(y-y1)*(y-y1))<((x-x2)*(x-x2)+(y-y2)*(y-y2))) {
					return new Point2D.Double(x1,y1);
				}
				else {
					return new Point2D.Double(x2,y2);
				}
		}
	}

}
